$(document).ready(function() {

    //function加载顺序
    //1、check_operator() 检查运营商
    //2、show_operator() 显示运营商
    //3、refresh_recharge_box() 刷新套餐

    localStorage.removeItem("credit_value");

    $('#rechargeTypeInfo').modal('show');

    // 验证手机号
    function isPhoneNo(phone) {
        var pattern = /^((0[6|8|9]))\d{8}$/;
        return pattern.test(phone);
    }

    $(".recharge-input input").bind("input propertychange",function(e){
        //判断输入号码后才出现清空图标
        if($(this).val().length > 0) {
            $('.clear-recharge-num').show();
        } else {
            $('.clear-recharge-num').hide();
        }

        //复制粘贴的号码里如果有括号，清理掉
        if($(this).val().indexOf("(") >= 0 || $(this).val().indexOf(")") >= 0) {
            $(this).val($(this).val().replace("(",""));
            $(this).val($(this).val().replace(")",""));
        }

        if($(this).val().length === 3 || $(this).val().length === 7) {
            var val = $(this).val();
            val += ' ';
            $(this).val(val);
        }

        if($(this).val().replace(/\s*/g,"").length > 10) {
            var str = $(this).val().replace(/\s*/g,"").substr(0,10);
            $(this).val(str);
        }

        if($(this).val().replace(/\s*/g,"").length === 10) {
            var user_num = $(this).val().replace(/\s*/g,"");
            check_operator(user_num);
        }

        //删除的时候，删除中间多余的空格
        $(this).on("keyup", function (e) {
            var e = e ? e : event;
            var k = e.keyCode || e.which;
            if (k == 8) {
                if($(this).val().length === 4 || $(this).val().length === 8) {
                    //删除前后的空格即可
                    $(this).val($(this).val().trim())
                }
            }
        });
    })


    //检查运营商
    function check_operator(cellphone)
    {
        //效验是否泰国号码
        if(isPhoneNo(cellphone)) {
            //复制粘贴的号码没有空格，处理一下，格式化号码
            if($('#rechargeNum').val().indexOf(" ") < 0) {
                var a = $('#rechargeNum').val().substr(0,3);
                var b = $('#rechargeNum').val().substr(3,3);
                var c = $('#rechargeNum').val().substr(6,4);
                $('#rechargeNum').val(a + ' ' + b + ' ' + c);
            }

            $('#waitForPost').modal('show');
            $.ajax({
                url: "/recharge/check-operator",
                type: "GET",
                data: {
                    "cellphone" : cellphone,
                },
                // complete:function(error) {
                //     if (error['status']  === 500) {
                //         $('.alert-danger').show().find('span').text('服务器未响应，请稍后再试');
                //         $('.alert-danger').fadeOut(6000);
                //     }
                // },
                success:function(data){
                    if(data.result == 'error') {
                        $('#waitForPost').modal('hide');
                        //允许手动选择运营商
                        $('.recharge-operators').addClass('canManual');
                        $('#manualSelectMy').modal('show');
                    } else {
                        show_operator(data.result.toUpperCase());
                        refresh_recharge_box(data.result.toUpperCase());
                        $('.recharge-operators').attr("data-opteror", data.result.toUpperCase());
                    }
                }
            })
        } else {
            $('.alert-warning').show().find('span').text('请输入正确的泰国手机号码');
            $('.alert-warning').fadeOut(6000);
        }
    }

    //显示运营商
    function show_operator(operator)
    {

        var operators_num = $('.recharge-operators li').length;

        for(i=0;i<operators_num;i++) {
            if($('.recharge-operators li').eq(i).attr('data-operator') == operator)
            {
                $('.recharge-operators li').removeClass('active').find('i').remove();
                //允许手动选择运营商
                $('.recharge-operators').addClass('canManual');
                $('.recharge-operators li').eq(i).addClass('active');
                $('.recharge-operators li').eq(i).html('<i class="fas fa-check"></i> ' + $('.recharge-operators li').eq(i).text());
            }
        }

        //DTAC、TRUEMOVE才显示类型选择
        if(operator == 'DTAC' || operator == 'TRUEMOVE') {
            $('#rechargeType').removeAttr('disabled');
        } else {
            $('#rechargeType').attr('disabled','disabled');
            $("#rechargeType").val('mtopup');
        }

    }

    //刷新对应套餐
    function refresh_recharge_box(operator) {
        $.ajax({
            url: "/recharge/show-package",
            type: "GET",
            data: {
                "operator" : operator,
                "recharge_type" : $("#rechargeType").val()
            },
            success:function(data){
                //渲染充值页面
                $(".recharge-phone-box").removeClass('num-disable')
                $(".recharge-phone-ul").html(data['html']);
                //渲染流量页面
                $(".recharge-web-box").removeClass('num-disable')
                $(".recharge-web-box").html(data['html_web']);
                //重新加载推广
                invit_item();
                $('#waitForPost').modal('hide');
            }
        })
    }

    //手动选择运营商
    $(document).on('click','.canManual li',function(e) {
        $('.canManual li').removeClass("user-manual-selected");
        $(e.target).addClass("user-manual-selected");
        $('#manualSelectOperator').modal('show');
    })

    //点击确认
    $(".ensureManualSelectOperator").click(function() {
        $('.recharge-operators li').removeClass('active').find('i').remove();
        $('.user-manual-selected').addClass('active');
        $('.user-manual-selected').html('<i class="fas fa-check"></i> ' + $('.user-manual-selected').attr("data-operator"));
        $('#manualSelectOperator').modal('hide');
        //重新标记运营商
        $('.recharge-operators').attr("data-opteror", $('.user-manual-selected').attr("data-operator").trim());
        //重新读取套餐
        refresh_recharge_box($('.user-manual-selected').attr("data-operator").trim());
    })

    function manual_select_operator(operator)
    {
        refresh_recharge_box(operator);
    }

    //选择历史号码
    $('.recharge-history-select li').click(function(e) {
        $('.recharge-history-select li').removeClass('active');
        $(e.target).addClass('active');
        $('.recharge-input i').show();
        $('.recharge-input input').val(e.target.dataset.phonenum.replace(/^(.{3})(.*)(.{4})$/, '$1 $2 $3'));
        check_operator(e.target.dataset.phonenum);
    })

    //点击清空图标，清空用户输入内容
    $('.recharge-input i').click(function() {
        $('.recharge-input input').val('');
        $('.recharge-input i').hide();
        $('.recharge-select-inner').addClass('num-disable');
        //重置运营商
        $('.recharge-operators').removeClass('canManual');
        $('.recharge-operators li').removeClass('active');
        $('.recharge-operators').find('i').remove();
        //充值历史号码
        $('.recharge-history-select li').removeClass('active');
    })

    //tab切换
    $('.recharge-phone').click(function() {
        $(this).addClass('active')
        $('.recharge-web').removeClass('active')
        $('.recharge-web-box').hide();
        $('.recharge-phone-box').show();
        $('.recharge-tab ul').attr('data-is-aop', 0);
        $("#rechargeType").removeAttr('disabled');
    })

    $('.recharge-web').click(function() {
        $(this).addClass('active')
        $('.recharge-phone').removeClass('active')
        $('.recharge-phone-box').hide();
        $('.recharge-web-box').show();
        $('.recharge-tab ul').attr('data-is-aop', 1);
        $("#rechargeType").val('mtopup');
        $("#rechargeType").attr('disabled','disabled');
    })

    //支付弹窗
    $(document).on('click','.recharge-select-items li',function() {
        if(isPhoneNo($(".recharge-input input").val().replace(/\s*/g,""))) {
            if($(this).hasClass('select-item')) {
                $('#payBox').modal('show');
                $('.pay-checkout small').hide();
                $('.ensure-order').text($(this).find("pre").text());
                $('.ensure-num').text($(".recharge-input input").val());
                $('.ensure-th').text($(this).find("span").attr("data-recharge-value-th") + "泰铢");
                //保存当前选中的金额到本地存储，方便其他期房调用
                localStorage.setItem("ensure-cn",$(this).find("i").attr("data-recharge-value"));
                $('.ensure-cn').text(localStorage.getItem("ensure-cn"));
                $('.ensure-opteror').text($('.recharge-operators').attr("data-opteror"));
                $('.pay-detail').attr('data-recharge-id',$(this).attr('data-recharge-id'));

                //判断订单是否超过20元
                if($(this).find("i").attr("data-recharge-value") <= 20) {
                    console.log($(this).find("i").attr("data-recharge-value"));
                    $('#creditEnoughSwitch').attr('disabled','disabled');
                    $('.enough-label').addClass('order-less-20');
                } else {
                    $('#creditEnoughSwitch').removeAttr('disabled');
                    $('.enough-label').removeClass('order-less-20');
                }

                //判断是否显示套餐介绍
                if($(this).hasClass('recharge-web')) {
                    $('.web-desc').removeClass('d-none');
                    $('.web-desc-body').html($(this).find('p').html());
                } else {
                    $('.web-desc').addClass('d-none');
                }
            }
        } else {
            if($(this).hasClass('select-item')) {
                $('.alert-warning').show().find('span').text('请输入正确的泰国手机号码');
                $('.alert-warning').fadeOut(6000);
            }
        }
    });

    //积分推广
    function invit_item() {
        $content = '<li class="invit"><span>邀请好友</span><i>积分抵话费</i></li>';
        $('.recharge-phone-box li').eq(0).before($content);
        $('.recharge-web-box li').eq(0).before($content);
    }

    //初始化加载推广按钮
    invit_item();

    $('#closePay').click(function() {
        $('#payBox').modal('hide');
        //重置积分开关，避免更换套餐的时候选中
        $('.custom-control-input').prop('checked', false);
    });

    //积分规则
    $('.credit-fa').click(function() {
        $('#creditInfo').modal('show');
    })

    //积分海报
    $(document).on('click','.invit',function() {
        $('#waitForPost').modal('show');
        $.ajax({
            url: "/get-credit-img",
            type: "GET",
            data: {},
            success:function(data){
                $('#savePicModal').modal('show');
                $('#shareImg').attr('src', data['path']);
                $('#waitForPost').modal('hide');
            }
        })
    })

    //积分海报
    $(document).on('click','.invit-2',function() {
        $('#waitForPost').modal('show');
        $.ajax({
            url: "/get-credit-img",
            type: "GET",
            data: {},
            success:function(data){
                $('#creditInfo').modal('hide');
                $('#payBox').modal('hide');
                $('#savePicModal').modal('show');
                $('#shareImg').attr('src', data['path']);
                $('#waitForPost').modal('hide');
            }
        })
    })

    //类型提示选择
    $('.recharge-type-fa').click(function() {
        $('#rechargeTypeInfo').modal('show');
    })

    $('.credit-ok').click(function() {
        $('#creditInfo').modal('hide');
    })

    //充值类型(预付费、后付费)选择
    $("#rechargeType").change(function(){
        if(isPhoneNo($(".recharge-input input").val().replace(/\s*/g,""))) {
            check_operator($(".recharge-input input").val().replace(/\s*/g,""));
        }
    });

    //确认支付
    $('.ensure-pay').click(function() {
        $.ajax({
            url: "/orders",
            type: "POST",
            data: {
                "recharge" : true,
                "recharge_package_id" : $('.pay-detail').attr('data-recharge-id'),
                "cellphone" : $(".recharge-input input").val().replace(/\s*/g,""),
                "is_AOP" : $('.recharge-tab ul').attr('data-is-aop').trim(),
                "recharge_type" : $("#rechargeType").val(),
                "credit_num" : parseFloat(localStorage.getItem("credit_value")*100)
            },
            complete:function(error){
                var json=JSON.parse(error.responseText);
                if (error['status']  === 400) {
                    layer.open({
                        content: json.msg,
                        skin: 'msg',
                        time: 3 //2秒后自动关闭
                    });
                }
            },
            success:function(data){
                WeixinJSBridge.invoke(
                    'getBrandWCPayRequest', data,
                    function(res){
                        window.location.href = "/recharge/record";
                        if(res.err_msg == "get_brand_wcpay_request：ok" ) {
                            // 使用以上方式判断前端返回,微信团队郑重提示：
                            // res.err_msg将在用户支付成功后返回
                            // ok，但并不保证它绝对可靠。
                        }
                    }
                );
            }
        })
    });

    //积分不足提示
    $('.credit-control-input-disable').click(function() {
        layer.open({
            content: '积分不足100，不能抵扣'
            ,skin: 'msg'
            ,time: 3 //2秒后自动关闭
        });
    })

    //积分不足提示
    $(document).on('click','.order-less-20',function() {
        layer.open({
            content: '订单金额不足20元，不能抵扣'
            ,skin: 'msg'
            ,time: 3 //2秒后自动关闭
        });
    })

});
